package com.airclick.merchant.controller;

import com.airclick.merchant.entity.Commercial;
import com.airclick.merchant.entity.MerDomain;
import com.airclick.merchant.service.CommercialService;
import com.airclick.merchant.service.MerService;
import com.airclick.merchant.serviceFeign.WalletServiceFeign;
import com.airclick.merchant.utils.*;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping({"/api/merchant"})
@Api(value = "商户管理接口", tags = {"商户"})
@ApiResponses(value = {
        @ApiResponse(code = 0000, message = "" ,response = MerDomain.class)
})
public class MerchantServeController {


    @Resource
    private MerService merService;

    @Resource
    private CommercialService commercialService;

    @Resource
    private WalletServiceFeign walletServiceFeign;

    @Value("${walletin}")
    private String withDrawUrl;

    @PostMapping(value = "/selectUserList")
    @ApiOperation("运营后台商户服务查询")
    public Object merDomainList(String status,String startTime , String endTime,@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum ,
                                @RequestParam(value = "pageSize",defaultValue = "6")Integer pageSize ){

        Map<String,Object> map = new HashMap<>();

        CommonResult merDomainCommon = merService.merDomainCommon(status,startTime,endTime,pageNum,pageSize);
        List<MerDomain> merDomainList = (List<MerDomain>) merDomainCommon.getData();

        for (MerDomain merDomain : merDomainList) {
            List<Commercial> merchantName = commercialService.selectMerchantName(merDomain.getId());
            for (Commercial merchant :merchantName){
                if (merchant.getMerchantName() != null) {
                    merDomain.setMerchantName(merchant.getMerchantName());
                }
                if (merchant.getId() != null){
                    merDomain.setMerchantCode(merchant.getId());
                }
            }
        }

        if (merDomainList.size() > 0) {
            map.put("merDomainList",merDomainList);
            return CommonResult.success(map,merDomainCommon.getDataCount());
        }else {
            return CommonResult.success(Constants.ERROR_NO_DATA_MSG);
        }

    }


    @PostMapping(value = "/selectUser")
    @ApiOperation("运营后台商户服务查询详情信息")
    public Object merDomainUser(String id){

        Map<String,Object> map = new HashMap<>();
        MerDomain merDomainList = merService.merDomainUser(id);

        if (merDomainList != null) {
            map.put("merDomainList",merDomainList);
            return CommonResult.success(map);
        }else {
            return CommonResult.failed(Constants.ERROR_NO_DATA_MSG);
        }
    }


    @PostMapping(value = "/updateUser")
    @ApiOperation("运营后台商户服务修改账号状态")
    public Object updateUser(String id,String status, String note){
        int updateUser = merService.updateUser(id,status,note);
        if (updateUser > 0) {
            return CommonResult.success(Constants.SUCCESS_MSG);
        }else {
            return CommonResult.failed(Constants.ERROR_MSG);
        }
    }


    @PostMapping(value = "/saveUser")
    @ApiOperation("运营后台商户服务创建")
    @Transactional(rollbackFor = Exception.class)
    public Object saveUser(String userName,String password , String email){
        try {
            MerDomain merUser = merService.selectId(userName);
            if (merUser == null) {
                String merUserEmail = merService.merUserEmail(userName);
                if (merUserEmail != null) {
                    return CommonResult.failed("邮箱已存在");
                }
                MerDomain updateUser = merService.addUser(userName,password,email);
                if (updateUser !=null) {
                    Commercial addCommercial = commercialService.saveCommercial(updateUser.getId(),email);
                    if (addCommercial == null) {
                        return CommonResult.failed("关联新增失败");
                    }
                    String sendWallet = "email="+email+"&password="+password;
                    String result1 = HttpClientUtils.doPostWithdraw(withDrawUrl + "/api/user/saveGameVsUser?", sendWallet);
//            logger.info("到钱包----------------"+withDrawUrl + "/api/updateWallet?"+sendWallet);
                    JSONObject jo = JSONObject.parseObject(result1);
                    if(Constants.SUCCESS.equals(jo.get("status"))){
                        String walletId = jo.get("data").toString();
                        int updateCommer = commercialService.update(addCommercial.getId(),walletId);
                        if (updateCommer > 0) {

                            return CommonResult.success(addWallet(updateUser.getId()));
                        }
                        return CommonResult.success(jo);
                    }
                    return CommonResult.success("新增关联表成功");
                }else {
                    return CommonResult.failed("新增失败");
                }
            }else {
                return CommonResult.failed("账号已存在");
            }
        }catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return CommonResult.failed(e.getMessage());
        }
    }

    public Object addWallet (String userId){
        HashMap<String, String> paramMap = new HashMap(4);
        paramMap.put("userId", userId);
        Map<String, String> linkmap = MapUtil.order(paramMap);
        String srcSign = MapUtil.mapJoin(linkmap, false, false);
        String sign = SecurityUtil.md5Hex(srcSign,true);

        System.out.println("updateUser.getId() = " + userId);
        System.out.println("sign = " + sign);
        CommonResult addWallet = walletServiceFeign.addWallet(userId,sign);
        return addWallet;
    }

    @PostMapping(value = "/updatePassword")
    @ApiOperation("修改密码")
    public CommonResult changepassword(String userName , String password ,String newpassword){


        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //查询有没有这个账号
        String merDomain = merService.findAllByUsername(userName);

        if (merDomain == null) {
            return CommonResult.failed(Constants.USER_BAN);
        }else {
            //判断原密码是否正确
            if (passwordEncoder.matches(password , merDomain)) {
                //新密码加密
                String encodePassword = passwordEncoder.encode(newpassword);
                //修改密码
                int count = merService.updatePassword(userName,encodePassword);
                //判断是否修改成功
                if (count > 0) {
                    return CommonResult.success(Constants.SUCCESS_MSG);
                }else{
                    return CommonResult.failed(Constants.ERROR_MSG);
                }
            }else{
                return CommonResult.failed(Constants.THE_OLD_PASSWORD_IS_INCORRECT);
            }
        }
    }

}
